package com.zzzzzz.plugins.shiro;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zzzzzz.core.datagrid.BaseData;
import com.zzzzzz.oms.GCS;
import com.zzzzzz.sys.user.UserService;

@Controller
public class SecurityWeb {
	
	@Resource
	private UserService userService;
	
	@RequestMapping(value="/login",method = RequestMethod.GET)
	public String login() {
		if(SecurityUtils.getSubject().isAuthenticated()){
			return "redirect:/";
		}
		return "login";
	}

	@RequestMapping(value="/login",method = RequestMethod.POST)
	public String fail(@RequestParam(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM) String userName, Model model) {
		model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM, userName);
		return "login";
	}

    @RequestMapping("/logout")
    public String processLogout() {
		SecurityUtils.getSubject().logout(); //removes all identifying information and invalidates their session too.
        return "redirect:/login";
    }
    
    @RequestMapping(value = "/changepassword", method = RequestMethod.POST)
	@ResponseBody
	public BaseData save(@RequestBody @Valid ChangePasswordForm changePasswordForm, BindingResult bindingResult) throws Exception {
		if (bindingResult.hasErrors()) {
			return new BaseData(GCS.ERRCD_PARAM);
		}

		BaseData baseData = userService.changePassword(changePasswordForm);
		return baseData;
	}
}
